package cn.piggy.type;

import cn.piggy.util.ObjectMapperUtil;
import cn.piggy.util.OkHttpClientUtil;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import java.io.IOException;

public abstract class AiTypeBase implements AiType {
    public abstract String getHost(Object object) throws IOException;

    @Override
    public Request getRequestObject(Object object) throws IOException {
        String json = ObjectMapperUtil.getObjectMapper().writeValueAsString(object);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody requestBody = RequestBody.create(json, mediaType);
        String token = getToken();
        String host = getHost(object);
        return new Request.Builder()
                .url(host +"?access_token=" + token)
                .method("POST", requestBody)
                .build();
    }



    public abstract String queryToken() throws IOException;

    public String getToken() throws IOException {
        return queryToken();
    }

    public String requestToken(Request request) throws IOException {
        Response execute = OkHttpClientUtil.getOkHttpClient().newCall(request).execute();
        ResponseBody body = execute.body();
        if(body!=null){
            String string = body.string();
            JSONObject jsonObject = JSONObject.parseObject(string);
            return jsonObject.getString("access_token");
        }
        throw new RuntimeException();
    }
}
